package main

import (
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

var (
	router *gin.Engine
)

func init() {
	router = gin.Default()
	router.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusNotFound, map[string]interface{}{
			"error": "Not Found API router",
		})
	})
}

func main() {

	check := router.Group("/check")
	{
		check.GET("/health", health)
	}
	go func() {
		checkServer()
		fmt.Println("路由部署成功")
	}()
	router.GET("/do/service",
		func(c *gin.Context) {
			c.JSON(200, map[string]interface{}{
				"msg": "successful",
			})
		})
	router.Run(":8080")
}

func health(c *gin.Context) {
	c.JSON(200, gin.H{
		"Message": "ok",
		"Wechat":  "1414100586",
		"QQ":      "1414100586",
	})
}
func checkServer() error {
	for i := 0; i < 10; i++ {
		resp, err := http.Get("http://127.0.0.1:8080/check/health")
		if resp.StatusCode == http.StatusOK && err == nil {
			return nil
		} else {
			fmt.Printf("Server error")
			time.Sleep(time.Second * 1)
		}
	}
	return errors.New("无法找到路由")
}
